package models

import (
	"errmsg"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"time"
	"tools"
)

type Family struct {
	Id         string `orm:"column(id);pk" json:"id" form:"id"`
	Sta        string `orm:"column(sta)" json:"sta" form:"sta"`
	UserId     string `orm:"column(user_id)" json:"user_id" form:"user_id"`
	FromUserId string `orm:"column(from_user_id)" json:"from_user_id" form:"from_user_id"`
	Status     int    `orm:"column(status)" json:"status" form:"status"`
	Name       string `orm:"column(name)" json:"name" form:"name"`
	SceneId    string `orm:"column(scene_id)" json:"scene_id" form:"scene_id"`
	CreateTime int64  `orm:"column(create_time)" json:"create_time" form:"create_time"`
	UpdateTime int64  `orm:"column(update_time)" json:"update_time" form:"update_time"`
}

var (
	Family_Wait    = 0 // 等待接受邀请
	Family_Accept  = 1 // 接受邀请
	Family_Refuse  = 2 // 拒绝接受邀请
	Family_Relieve = 3 // 已解除分享
)

func init() {
	orm.RegisterModel(new(Family))
}

func (m *Family) TableName() string {
	return "family"
}

func NewFamily() *Family {
	return &Family{}
}

func GetFamilyById(id string) (*Family, error) {
	f := &Family{Id: id}
	err := orm.NewOrm().Read(f)
	if err == orm.ErrNoRows {
		return nil, nil
	}
	if err != nil {
		logs.Error(err)
		return nil, err
	}
	return f, nil
}

func GetFamilyByUidAndSta(uid, sta string) (*Family, error) {
	f := &Family{}
	err := orm.NewOrm().QueryTable(NewFamily().TableName()).Filter("user_id", uid).Filter("sta", sta).One(f)
	if err == orm.ErrNoRows {
		return nil, nil
	}
	if err != nil {
		logs.Error(err)
		return nil, err
	}
	return f, nil
}

// 获取多行家人
func GetAllFamily(params map[string]interface{}, page int) ([]*Family, error) {
	var (
		lists []*Family
		qs    orm.QuerySeter
		err   error
	)

	qs = orm.NewOrm().QueryTable(NewFamily().TableName()).OrderBy("-create_time")

	if len(params) > 0 {
		for k, v := range params {
			qs = qs.Filter(k, v)
		}
	}

	if page > 0 {
		row := beego.AppConfig.DefaultInt("page_limit", 20)
		start := (page - 1) * row
		qs = qs.Limit(row).Offset(start)
	}

	if _, err = qs.All(&lists); err != nil {
		logs.Error(err)
		return nil, err
	}

	if len(lists) == 0 {
		return nil, nil
	}

	return lists, nil
}

// 解除设备分享
func RelieveFamilyBySta(sta string, uid ...string) error {
	var (
		lists   []*Family
		err     error
		content string
		p       map[string]interface{}
		s       []interface{}
		sql     string
	)

	p = make(map[string]interface{})
	p["sta"] = sta
	p["status__in"] = []int{0, 1}

	if len(uid) > 0 {
		p["user_id"] = uid[0]
	}

	// 找出设备所有分享
	lists, err = GetAllFamily(p, 0)
	if err != nil {
		logs.Error(err)
		return err
	}
	if lists == nil {
		return nil
	}

	// 指定用户的时候，修改状态     否则设备为重新匹配，需要删除所有的分享用户
	if len(uid) > 0 {
		sql = `UPDATE family SET status = ?, update_time = ? WHERE sta = ? and status in (0, 1)`
		s = append(s, Family_Relieve, time.Now().Unix(), sta)
		if len(uid) > 0 {
			sql += " and user_id = ?"
			s = append(s, uid[0])
		}
	} else {
		sql = "delete from `family` where `sta` = ?"
		s = append(s, sta)
	}

	_, err = orm.NewOrm().Raw(sql, s...).Exec()
	if err != nil {
		logs.Warn(err)
		return err
	}

	// 通知
	for _, v := range lists {
		if v.Status == Family_Accept {
			content = fmt.Sprintf("您的分享设备(%s)已被解除", v.Name)
		} else {
			content = fmt.Sprintf("您的设备(%s)分享邀请已被撤销", v.Sta)
		}
		// 推送消息
		PushMessage(v.UserId, content, "message")
	}

	return nil
}

// 修改分享状态
func UpdateFamilyStatusById(id string, act int) error {
	sql := `UPDATE family SET status = ?, update_time = ? WHERE id = ?`
	_, err := orm.NewOrm().Raw(sql).SetArgs(act, time.Now().Unix(), id).Exec()
	if err != nil {
		logs.Warn(err)
		return err
	}
	return nil
}

// 更新家人
func UpdateFamily(f *Family) bool {
	f.UpdateTime = time.Now().Unix()
	c, err := orm.NewOrm().Update(f)
	if err != nil {
		logs.Error(err)
		return false
	}
	if c == 0 {
		return false
	}
	return true
}

// 添加家人
func AddFamily(from_uid, uid, sta string) error {
	f := &Family{
		Id:         tools.GUUID(),
		Sta:        sta,
		UserId:     uid,
		FromUserId: from_uid,
		CreateTime: time.Now().Unix(),
		Status:     Family_Wait,
	}
	if _, err := orm.NewOrm().Insert(f); err != nil {
		logs.Error(err)
		return err
	}
	return nil
}

// 是否重复分享
func IsRepeatShare(sta, uid string) (bool, error) {
	count, err := orm.NewOrm().QueryTable("family").Filter("sta", sta).Filter("user_id", uid).Filter("status__in", []int{0, 1}).Count()
	if err != nil {
		logs.Error(err)
		return false, err
	}
	if count == 0 {
		return false, nil
	}
	return true, nil
}

// 获取我的家人
func GetMyFamilyUsers(uid string) ([]*User, error) {
	// 分享给我的用户
	sql := `select u.* FROM user u LEFT JOIN family f on u.id = f.from_user_id WHERE f.user_id = ? and f.status = 1 GROUP BY u.id`
	sql += " union all "
	// 我分享出去的用户
	sql += `SELECT u.* FROM user u left JOIN family f on u.id = f.user_id WHERE f.from_user_id = ? and f.status = 1 GROUP BY u.id`

	lists := []*User{}
	if _, err := orm.NewOrm().Raw(sql).SetArgs(uid, uid).QueryRows(&lists); err != nil {
		logs.Error("GetMyFamilyUsers error:", err)
		return nil, err
	}
	if len(lists) == 0 {
		return nil, nil
	}
	return lists, nil
}

// 判断用户是否我的家人
func IsMyFamily(uid, myid string) (bool, error) {
	sql := `select u.* FROM user u LEFT JOIN family f on u.id = f.from_user_id WHERE f.user_id = ? and u.id = ? and f.status = 1 GROUP BY u.id`
	sql += " union all "
	// 我分享出去的用户
	sql += `SELECT u.* FROM user u left JOIN family f on u.id = f.user_id WHERE f.from_user_id = ? and u.id = ? and f.status = 1 GROUP BY u.id`

	lists := []*User{}
	if _, err := orm.NewOrm().Raw(sql).SetArgs(myid, uid, myid, uid).QueryRows(&lists); err != nil {
		logs.Error("IsMyFamily error:", err)
		return false, errmsg.ErrResponseSystem
	}
	if len(lists) == 0 {
		return false, nil
	}
	return true, nil
}
